package com.linln.wxapi;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import com.linln.common.utils.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import com.linln.common.constant.UrlConst;
import com.linln.common.enums.TypeEnum;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.domain.MemberOrder;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberOrderService;
import com.linln.wxapi.config.ReturnPayInfoVO;
import com.linln.wxapi.config.WeChatPayProperties;

/**
 * @author : Gentle
 * @date : 2019/5/17 12:11
 * @description:
 */
@RestController
@RequestMapping(value = "/wx/pay/{area}")
public class WeChatPayController {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    WeChatPayProperties weChatPayProperties;
    @Autowired
    private  MemberOrderService orderService;
   
    /**
     * 此处处理订单信息，构建订单数据。ReturnPayInfoVO
     *
     * 将构建好的支付参数返回到前端，前端调起微信支付
     * @return
     */
    @RequestMapping(value = "/pay",method = {RequestMethod.GET,RequestMethod.POST})
    public  ResultVo weChatPay(
    		String openId,
    		String money,
    		String orderdesc,
    		String orderId,
    		Long memberId,
    		Integer type,//类型
    		Long typeId,//类型id
    		String formId,
    		String county,//所选择的城市
    		@PathVariable String area
    		) {
    	
    	System.out.println("openId===="+openId); 
    	System.out.println("memberId===="+memberId);  
    	System.out.println("type===="+type); 
    	System.out.println("typeId===="+typeId);  
    	System.out.println("formId===="+formId);  
    	System.out.println("county===="+county); 
    	System.out.println("orderId===="+orderId);  


    	
        /**
         * 处理内部业务，校验订单等
         */
        final WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = WxPayUnifiedOrderRequest.newBuilder()
                //调起支付的人的 openId
                .openid(openId)
                //订单编号
                .outTradeNo(orderId)
                .tradeType("JSAPI")
                //订单金额
                .totalFee(yuanToFee(new BigDecimal(money)))
                //商品描述
                .body(orderdesc)
                //获取本地IP
                .spbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress())
                //回调的 URL 地址
                .notifyUrl(UrlConst.NOTICEURL)
                .build();
        WxPayUnifiedOrderResult wxPayUnifiedOrderResult =null;
        try {
            wxPayUnifiedOrderResult = wxPayService.unifiedOrder(wxPayUnifiedOrderRequest);
          //组合参数构建支付
            Map<String, String> paySignInfo = new HashMap<>(5);
            String timeStamp = createTimestamp();
            String nonceStr = String.valueOf(System.currentTimeMillis());
            paySignInfo.put("appId", weChatPayProperties.getAppId());
            paySignInfo.put("nonceStr", nonceStr);
            paySignInfo.put("timeStamp", timeStamp);
            paySignInfo.put("signType", "MD5");
            String prepay_id=wxPayUnifiedOrderResult.getPrepayId();
            paySignInfo.put("package", "prepay_id=" + prepay_id);
            String paySign = SignUtils.createSign(paySignInfo, "MD5", weChatPayProperties.getMchKey(),null);
            System.out.println("prepay_id======="+prepay_id);
            //组合支付参数
            ReturnPayInfoVO returnPayInfoVO = new ReturnPayInfoVO();
            returnPayInfoVO.setAppId(weChatPayProperties.getAppId());
            returnPayInfoVO.setNonceStr(nonceStr);
            returnPayInfoVO.setPaySign(paySign);
            returnPayInfoVO.setSignType("MD5");
            returnPayInfoVO.setPrepayId(prepay_id);
            returnPayInfoVO.setTimeStamp(timeStamp);
            MemberOrder memberOrder=orderService.findByOrderCode(orderId);
            if(memberOrder==null) {
            	memberOrder=new MemberOrder();
            	memberOrder.setArea(area);
            	MemberInfo member=new MemberInfo();
            	member.setId(memberId);
             	memberOrder.setMember(member);
            	memberOrder.setMoney(Double.valueOf(money));
            	memberOrder.setOrderCode(orderId);
            	memberOrder.setPayStatus(0);
            	memberOrder.setType(type);
            	memberOrder.setTypeId(typeId);
            	String typeinfo=TypeEnum.getVal(type);
            	if(type.intValue()==TypeEnum.AGENT.getCode().intValue()) {
                	memberOrder.setContent("支付代理费用"); 
                	memberOrder.setArea(county); 
            	}else {
                	memberOrder.setContent("购买"+typeinfo+"置顶费用"); 
            	}
            	memberOrder.setPrepay_id(formId);             	
            	orderService.save(memberOrder);
            }            
        	// return returnPayInfoVO;
            return ResultVoUtil.success(returnPayInfoVO);
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new RuntimeException("微信支付调起失败！");
        }
        
        
       

    }




    /**
     * 此处处理订单信息，构建订单数据。ReturnPayInfoVO
     *
     * 将构建好的支付参数返回到前端，前端调起微信支付
     * @return
     */
    @RequestMapping(value = "/payRenew",method = {RequestMethod.GET,RequestMethod.POST})
    public  ResultVo weChatRenewPay(
            String openId,
            String money,
            String orderdesc,
            Long memberId,
            Integer type,//类型
            Long typeId,//类型id
            String formId,
            String county,//所选择的城市
            @PathVariable String area
    ) {

        System.out.println("openId===="+openId);
        System.out.println("memberId===="+memberId);
        System.out.println("type===="+type);
        System.out.println("typeId===="+typeId);
        System.out.println("formId===="+formId);
        System.out.println("county===="+county);

        //创建续费订单
        MemberOrder memberOrder=new MemberOrder();
        String orderId = ToolUtil.getRandomString(32);
            memberOrder.setArea(area);
            MemberInfo member=new MemberInfo();
            member.setId(memberId);
            memberOrder.setMember(member);
            memberOrder.setMoney(Double.valueOf(money));
            memberOrder.setOrderCode(orderId);
            memberOrder.setPayStatus(0);
            memberOrder.setType(type);
            memberOrder.setTypeId(typeId);
            String typeinfo=TypeEnum.getVal(type);
            if(type.intValue()==TypeEnum.AGENT.getCode().intValue()) {
                memberOrder.setContent("支付代理费用");
                memberOrder.setArea(county);
            }else {
                memberOrder.setContent("续费"+typeinfo+"置顶");
            }
            memberOrder.setPrepay_id(formId);
            orderService.save(memberOrder);


        /**
         * 处理内部业务，校验订单等
         */
        final WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = WxPayUnifiedOrderRequest.newBuilder()
                //调起支付的人的 openId
                .openid(openId)
                //订单编号
                .outTradeNo(orderId)
                .tradeType("JSAPI")
                //订单金额
                .totalFee(yuanToFee(new BigDecimal(money)))
                //商品描述
                .body(orderdesc)
                //获取本地IP
                .spbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress())
                //回调的 URL 地址
                .notifyUrl(UrlConst.NOTICEURL)
                .build();
        WxPayUnifiedOrderResult wxPayUnifiedOrderResult =null;
        try {
            wxPayUnifiedOrderResult = wxPayService.unifiedOrder(wxPayUnifiedOrderRequest);
            //组合参数构建支付
            Map<String, String> paySignInfo = new HashMap<>(5);
            String timeStamp = createTimestamp();
            String nonceStr = String.valueOf(System.currentTimeMillis());
            paySignInfo.put("appId", weChatPayProperties.getAppId());
            paySignInfo.put("nonceStr", nonceStr);
            paySignInfo.put("timeStamp", timeStamp);
            paySignInfo.put("signType", "MD5");
            String prepay_id=wxPayUnifiedOrderResult.getPrepayId();
            paySignInfo.put("package", "prepay_id=" + prepay_id);
            String paySign = SignUtils.createSign(paySignInfo, "MD5", weChatPayProperties.getMchKey(),null);
            System.out.println("prepay_id======="+prepay_id);
            //组合支付参数
            ReturnPayInfoVO returnPayInfoVO = new ReturnPayInfoVO();
            returnPayInfoVO.setAppId(weChatPayProperties.getAppId());
            returnPayInfoVO.setNonceStr(nonceStr);
            returnPayInfoVO.setPaySign(paySign);
            returnPayInfoVO.setSignType("MD5");
            returnPayInfoVO.setPrepayId(prepay_id);
            returnPayInfoVO.setTimeStamp(timeStamp);
            returnPayInfoVO.setOrderCode(orderId);
            // return returnPayInfoVO;
            return ResultVoUtil.success(returnPayInfoVO);
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new RuntimeException("微信支付调起失败！");
        }




    }


    /**
     * 校验订单支付状态
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/checkOrderPayStatus",method = {RequestMethod.GET,RequestMethod.POST})
    public ResultVo checkOrderPayStatus(String orderId){
        MemberOrder byOrderCode = orderService.findByOrderCode(orderId);
        for(Integer i = 0;i< 6;i++){
            if(!checkOrder(orderId)){
                try {
                    Thread.sleep(1000l);
                } catch (InterruptedException e) {

                }
            }
            if(checkOrder(orderId)){
                break;
            }

        }
        return ResultVoUtil.success(byOrderCode);
    }


    /**
     * 校验订单
     * @param orderId
     * @return
     */
    public  Boolean  checkOrder(String orderId){
        MemberOrder byOrderCode = orderService.findByOrderCode(orderId);
        if(byOrderCode == null || byOrderCode.getPayStatus().intValue() == 0){
            return false;
        }
        return true;
    }

  

    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}